package com.terry.sp.utils;

import com.terry.sp.core.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@Slf4j(topic = "FileHelper")
public class FileHelper {

    /**
     * 通过上传的文件名，缓冲到本地，后面才能解压、验证
     *
     * @param filePath 临时缓冲到本地的目录
     * @param file
     */
    public static boolean createLocalFile(String filePath, MultipartFile file) {
        File localFile = new File(filePath);

        if (!localFile.exists()) {  //如果目录不存在，先创建目录
            if (!localFile.mkdirs()) throw new ServiceException("目录创建失败!");
        }

        String originalFilename = file.getOriginalFilename();
        String path = filePath + "/" + originalFilename;

        log.info("将创建本地文件 路径: {}", path);
        localFile = new File(path);
        FileOutputStream fos = null;
        InputStream in = null;
        try {
            if (localFile.exists()) {
                //如果文件存在删除文件
                boolean delete = localFile.delete();
                if (!delete) {
                    log.error("删除已存在的文件失败: \"{}\"", path, new Exception("删除已存在文件失败： \"" + path));
                }
            }
            if (!localFile.exists()) //noinspection ResultOfMethodCallIgnored
                localFile.createNewFile();

            //创建文件成功后，写入内容到文件里
            fos = new FileOutputStream(localFile);
            in = file.getInputStream();
            byte[] bytes = new byte[1024];
            int len;
            while ((len = in.read(bytes)) != -1) {
                fos.write(bytes, 0, len);
            }

            fos.flush();
            log.info("本地文件创建成功!");
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                log.error("输入或输出流关闭失败: {}", e);
            }
        }
    }
}
